<?php
/**
 * 安全校验
 * 
 * @copyright	http://www.easymvc.com
 * @author 		光哥 <439884988@qq.com>
 * @version		1.0 - 2012-07-09
 * @package		Lib
 */
if(!defined('EASYMVC')) {
	exit('Access Denied');
}
/**
 * csrf
 */
class Lib_Csrf {
	
	const SALT = " easymvc is very good ";
	public static $input_name = "csrf_input_name";
	
	public static function getInstance(){
		static $obj;
		if(!$obj) $obj = new self();
		return $obj;
	}
	/**
	 * csrf 表单
	 * @param string $form_input_name
	 * @return string
	 */
	public function csrf_form(){
		$input_name = self::$input_name;
		$time = time();
		$hash = $time.hash("md5", $time.self::SALT); 
		
		$str = "<input type='hidden' name='{$input_name}' value='{$hash}'>";
		Lib_Session::getInstance()->set($input_name."_".$time,1);
		return $str;
	}
	/**
	 * csrf 校验,表单防刷
	 * @param string $csrf_string
	 * @return boolean
	 */
	public function csrf_check($csrf_string){	
		$input_name = self::$input_name;
		$time = substr($csrf_string,0,10);
		$hash = $time.hash("md5", $time.self::SALT);
	    if($csrf_string != $hash) return false;
	    $is_set =  Lib_Session::getInstance()->is_set($input_name."_".$time);
		if(!$is_set) return false;
		return true;
	}
}

?>